package com.printer.printerexample;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.media.ThumbnailUtils;
import android.os.Build;
import android.util.Log;

import com.rsk.api.RskApi;
import com.rsk.printerlibrary.ESC;
import com.rsk.printerlibrary.PrinterManager;
import com.rsk.printerlibrary.common.Printer_Params;


public class PrinterUtils {
    private static final String TAG = "PrinterUtils";
    private static final PrinterUtils mThis = new PrinterUtils();
    private static PrinterManager mManager = PrinterManager.getInstance();
    String version = "";

    public static PrinterUtils getInstance() {
        return mThis;
    }

    public static PrinterManager getManager() {
        return mManager;
    }

    int devType = 0;//设备型号

    boolean opened;//是否打开状态


    public boolean init() {
        if (opened) return opened;
        synchronized (mThis) {
            Log.d(TAG, "init: MODEL=" + Build.MODEL);
            mManager.powerOn();
            try{
                Thread.sleep(600);
            }catch (Exception e){
                e.printStackTrace();
            }
            String devSrial = "/dev/ttyMSM2";
            devType = RskApi.GetDevice();
            if (devType == 11 || devType == 14) {//R860 = 14
                devSrial = "/dev/ttyMSM2";
            } else if (devType == 8) {
                devSrial = "/dev/ttyHSL1";
            } else if (devType == 12) {
                devSrial = "/dev/ttyS0";
            } else if (devType == 15) {
                devSrial = "/dev/ttyHS1";
            }
            boolean op = mManager.openPort(devSrial, 115200);
            Log.d(TAG, "run: 串口打开结果 =" + op);
            opened = true;
        }
        return opened;
    }


    public void destroy() {
        synchronized (mThis) {
            mManager.closePort();
            mManager.powerOff();
            opened = false;
        }
    }
    //文本位置 0居左，1居中，2居右
    public void printText(String text, int alignment) {
        synchronized (mThis) {
            mManager.PrintInit();
            switch (alignment) {
                case 0:
                    mManager.PrintSetLayout(Printer_Params.ALIGN.LEFT);
                    break;
                case 1:
                    mManager.PrintSetLayout(Printer_Params.ALIGN.CENTER);
                    break;
                case 2:
                    mManager.PrintSetLayout(Printer_Params.ALIGN.RIGHT);
                    break;
            }
            mManager.PrintChars(text);
//            mManager.PrintLines(1);
        }
    }

    public static void printText(String text, int alignment, Printer_Params.TEXT_ENLARGE m) {
        synchronized (mThis) {
            mManager.PrintInit();
            switch (alignment) {
                case 0:
                    mManager.PrintSetLayout(Printer_Params.ALIGN.LEFT);
                    break;
                case 1:
                    mManager.PrintSetLayout(Printer_Params.ALIGN.CENTER);
                    break;
                case 2:
                    mManager.PrintSetLayout(Printer_Params.ALIGN.RIGHT);
                    break;
            }
            ESC.getInstance().setFontEnlarge(m);
            mManager.PrintChars(text);
//            mManager.PrintLines(1);
        }
    }

    public static void printBitmap(Bitmap bitmap, int alignment, int width, int height) {
        synchronized (mThis) {
            switch (alignment) {
                case 0:
                    mManager.PrintSetLayout(Printer_Params.ALIGN.LEFT);
                    break;
                case 1:
                    mManager.PrintSetLayout(Printer_Params.ALIGN.CENTER);
                    break;
                case 2:
                    mManager.PrintSetLayout(Printer_Params.ALIGN.RIGHT);
                    break;
            }
            if (bitmap == null) {
                Log.d(TAG, "printBitmap:  is null");
                return;
            }
            ESC esc = ESC.getInstance();
            int i = esc.printImage(bitmap);
            Log.d(TAG, "printBitmap: ret = " + i);
        }
    }


    public void printBlankLine(int num) {
        synchronized (mThis) {
            mManager.PrintLines(num);
        }
    }


    public void printQrCode(String text) {
        synchronized (mThis) {
            if (text == null) return;
            mManager.PrintSetLayout(Printer_Params.ALIGN.CENTER);
//            mManager.PrintQRWidth(6);
            if (text.length() > 150) {
                mManager.PrintQRPixel(4);
            } else {
                mManager.PrintQRPixel(6);
            }
            mManager.PrintQR(text);
//            mManager.PrintChars("\r\n");
        }
    }
//
//    
//    public void printQrCode(String text) {
//        Bitmap qrCodeBitmap = BitmapUtils.createQRCodeBitmap(text);
//        if (qrCodeBitmap == null) {
//            return;
//        }
//        synchronized (mThis) {
//            mManager.PrintSetLayout(Printer_Params.ALIGN.CENTER);
//            ESC esc = ESC.getInstance();
//            int i = esc.printImage(qrCodeBitmap);
//            Log.d(TAG, "printBitmap: ret = " + i);
//        }
//    }


    public void printBarCode(String text) {
        synchronized (mThis) {
            mManager.PrintSetLayout(Printer_Params.ALIGN.CENTER);
            mManager.PrintSet1DWidth(2);
            mManager.PrintCode128(text);
        }
    }


    public void hbdw() {
        Log.d(TAG, "hbdw: 未实现");
    }


    public void bgj() {
        //不干胶走纸
        Log.d(TAG, "bgj: ");
    }


    public boolean isOpened() {
        return opened;
    }

    public String getVersion() {
        if (!opened) return "";
        synchronized (mThis) {
            Log.d(TAG, "run: 串口打开类型 =" + devType);
            byte[] versionData = new byte[50];
            mManager.getVersion(versionData);
            final String versionStr = new String(versionData).trim();
            if (versionStr != null) {
                version = versionStr;
                Log.d(TAG, "run: 版本号：" + versionStr);
            }
        }
        return version;
    }


    /**
     * 对图片进行压缩（去除透明度）
     *
     * @param bitmapOrg
     */
    public static Bitmap compressPic(Bitmap bitmapOrg, int Width, int Height) {
        // 获取这个图片的宽和高
        int width = bitmapOrg.getWidth();
        int height = bitmapOrg.getHeight();
        // 定义预转换成的图片的宽度和高度
        int newWidth = Width;
        int newHeight = Height;
        Bitmap targetBmp = Bitmap.createBitmap(newWidth, newHeight, Bitmap.Config.ARGB_8888);
        Canvas targetCanvas = new Canvas(targetBmp);
        targetCanvas.drawColor(0xffffffff);
        targetCanvas.drawBitmap(bitmapOrg, new Rect(0, 0, width, height), new Rect(0, 0, newWidth, newHeight), null);
        return targetBmp;
    }


    @SuppressLint("NewApi")
    public static Bitmap convertToBlackWhite(Bitmap bmp) {
        int width = bmp.getWidth(); // 获取位图的宽
        int height = bmp.getHeight(); // 获取位图的高
        int[] pixels = new int[width * height]; // 通过位图的大小创建像素点数组

        bmp.getPixels(pixels, 0, width, 0, 0, width, height);
        int alpha = 0xFF << 24;
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int grey = pixels[width * i + j];

                int red = ((grey & 0x00FF0000) >> 16);
                int green = ((grey & 0x0000FF00) >> 8);
                int blue = (grey & 0x000000FF);

                grey = (int) (red * 0.3 + green * 0.59 + blue * 0.11);
                grey = alpha | (grey << 16) | (grey << 8) | grey;
                pixels[width * i + j] = grey;
            }
        }
        Bitmap newBmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);

        newBmp.setPixels(pixels, 0, width, 0, 0, width, height);

        Bitmap resizeBmp = ThumbnailUtils.extractThumbnail(newBmp, 460, 460);
        return resizeBmp;
    }

}
